package cn.com.zhuoyan.solr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrUtile {
	private static Logger logger=LoggerFactory.getLogger(SolrUtile.class);
	private String Url="http://localhost:8080/solr/core1";
	public HttpSolrClient start(){
		HttpSolrClient server=null;
		if(StringUtils.isEmpty(Url)){
			logger.error("solr server url is null");
			throw new RuntimeException("solr server url is null");
		}
		try {
			server = new HttpSolrClient(Url);
		} catch (Exception e) {
			new SolrServerException("Server refused connection at: "+Url+"");
		}
		return server;
	}
	
	public void delete(Map<String,String> map) throws Exception{
		HttpSolrClient server=start();
		try
		{
			if(map.isEmpty()){
				server.deleteByQuery("*:*");
			}else{
				Set<String> set=map.keySet();
				for(String key:set){
					String value=map.get(key);
					server.deleteByQuery(key+":"+value);
				}
			}
			server.commit();
		}
		catch (RuntimeException e)
		{
			logger.error("paramter is error");
			throw new RuntimeException("paramter is error");
		}finally{
			end(server);
		}
	}
	public <T> List<T> seacher(Map<String,String> map) throws Exception{
		HttpSolrClient server=start();
		List<T> list=new ArrayList<T>();
		SolrQuery query=new SolrQuery();
		try
		{
			if(map.isEmpty()){
				query.addField("*:*");
			}else{
				Set<String> set=map.keySet();
				for(String key:set){
					String value=map.get(key);
					query.setQuery(key+":"+value);
				}
			}
			QueryResponse res=server.query(query);
			for(SolrDocument doc:res.getResults()){
				System.out.println(doc.get("id")+",,,"+doc.get("s_name")+",,,"+doc.get("s_updateTime"));
			}
			server.commit();
		}
		catch (RuntimeException e)
		{
			logger.error("paramter is error");
			throw new RuntimeException("paramter is error");
		}finally{
			end(server);
		}
		return list;
	}
	public static void end(HttpSolrClient server){
		try {
			if (server != null) {
				server.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
